package com.feilong.edgeAI.service;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2024/3/22 11:35
 */
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class TcpFileTransferTask extends AsyncTask<Void, Void, String> {

    private static final String TAG = "TCPFileClient";
    public static final String FILE_SERVER_IP = "192.168.3.221";
    public static final int FILE_SERVER_PORT = 9527;
    private File fileToSend;
    private Context context;
    public TcpFileTransferTask(Context context,File fileToSend) {
        this.context = context;
        this.fileToSend = fileToSend;
    }

    @Override
    protected String doInBackground(Void... voids) {
        try (Socket socket = new Socket(FILE_SERVER_IP, FILE_SERVER_PORT);
             FileInputStream fis = new FileInputStream(fileToSend);
             DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
             DataInputStream dis = new DataInputStream(socket.getInputStream())) {

            dos.writeLong(fileToSend.length());

            // 发送文件内容
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                dos.write(buffer, 0, length);
                Log.d(TAG, "doInBackground: "+length);
            }
            dos.flush();

            // 接收服务端消息
            String serverResponse = dis.readUTF();
            Log.d(TAG, "doInBackground: "+serverResponse);
            return serverResponse;

        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        // 在这里处理服务端返回的消息，例如显示在UI上
        Toast.makeText(context, result, Toast.LENGTH_LONG).show();
    }

    // 初始化AsyncTask并开始发送文件
    public void startSending(Context context) {
        this.context = context;
        execute();
    }
}